<template>
  <div v-loading="pageLoading">
    <!-- 组委会 -->
    <div class="committee_info gl_fl">
      <header class="game_modal_header">组委会</header>
      <div style="padding-left: 40px;box-sizing: border-box;">
        <div v-loading="committeeLoading" class="committee_content modal_shadow">
          <div v-if="committionList.length" class="committee_list">
            <div v-for="(item, index) in committionList" :key="index" class="committee_item">
              <div class="title">{{ item.name }}</div>
              <div class="committee_item_content">
                <span v-for="(jtem, jndex) in item.data" :key="jndex" class="committee_name">{{ jtem.organizationName }}</span>
              </div>
            </div>
          </div>
          <div v-else class="no_data">暂无组委会相关信息</div>
        </div>
      </div>
    </div>
    <!-- 报名倒计时 -->
    <div class="entry_info gl_fl">
      <header class="game_modal_header">{{ entryTitle }}</header>
      <div style="padding-right: 40px;">
        <div class="entry_countdown modal_shadow">
          <count-down :deadline="deadline" @countDownEnd="countDownEnd" />
        </div>
      </div>
    </div>
    <div class="gl_clear" />
    <!-- 竞赛项目 -->
    <div class="category_info">
      <header class="game_modal_header">竞赛项目</header>
      <template v-if="categoryList.length">
        <div v-for="(item, index) in categoryList" :key="index" class="category_item modal_shadow gl_mb_10" :class="!item.fold ? 'active' : ''">
          <div class="category_title" @click="toggleFold(item, index)">
            <div>
              <img class="category_icon" :src="category_icon" alt="">
              <span class="category_name gl_ellipsis">{{ item.name }}</span>
            </div>
            <div>
              <span class="fold_name">{{ item.fold ? '展开' : '收起' }}</span>
              <img class="fold_icon" :class="!item.fold ? 'active' : ''" :src="fold_icon" alt="">
            </div>
          </div>
          <div class="category_content" :class="item.fold ? 'height_0' : ''">
            <div class="line" />
            <div class="event_group">
              <div v-for="jtem in item.eventGroups" :key="jtem.id" class="event_group_item">
                <div class="event_group_title">
                  {{ jtem.name }} ({{ jtem.startBirthDate && jtem.startBirthDate.substring(0, 10) }} 至 {{ jtem.endBirthDate && jtem.endBirthDate.substring(0, 10) }})
                </div>
                <div class="event_group_content">
                  <template v-if="jtem.events.length && (jtem.events[0].genderCode === 'M' || jtem.events[0].genderCode === 'W')">
                    <el-row style="margin: 10px 24px;">
                      <el-col class="name M" :span="2" style="width: 60px;">男子组：</el-col>
                      <el-col :span="22" style="width: calc(100% - 60px);">
                        <template v-for="ktem in jtem.events">
                          <span v-if="ktem.genderCode === 'M'" :key="ktem.id" class="event_item">{{ ktem.name }}</span>
                        </template>
                      </el-col>
                    </el-row>
                    <el-row style="margin: 10px 24px;">
                      <el-col class="name W" :span="2" style="width: 60px;">女子组：</el-col>
                      <el-col :span="22" style="width: calc(100% - 60px);">
                        <template v-for="ktem in jtem.events">
                          <span v-if="ktem.genderCode === 'W'" :key="ktem.id" class="event_item">{{ ktem.name }}</span>
                        </template>
                      </el-col>
                    </el-row>
                  </template>
                  <template v-else>
                    <el-row style="margin: 10px 24px;">
                      <el-col class="name M" :span="2" style="width: 70px;">具体级别：</el-col>
                      <el-col :span="22" style="width: calc(100% - 70px);">
                        <span v-for="ktem in jtem.events" :key="ktem.id" class="event_item">{{ ktem.name }}</span>
                      </el-col>
                    </el-row>
                  </template>
                </div>
              </div>
            </div>
          </div>
        </div>
      </template>
      <div v-else class="modal_shadow no_data">暂无竞赛项目</div>
    </div>
  </div>
</template>
<script>
import {
  api_GET_EventsManagementCompetitionWithRoute,
  api_GET_EventsManagementCompetitionOrganization,
  api_GET_EventsManagementCategory
} from '@/extend/api/gameswaggerApi/app';
import countDown from '@/plugin/countDown/index.vue';
import category_icon from '@/assets/images/category_icon.png';
import fold_icon from '@/assets/images/fold_icon.png';
export default {
  components: {
    countDown
  },
  data() {
    return {
      category_icon: category_icon,
      fold_icon: fold_icon,
      pageLoading: false,
      gameInfo: {},
      gameId: '',
      categoryList: [],
      committionList: [],
      /* === 倒计时相关 === */
      entryTitle: '',
      countDownTimer: null,
      // 倒计时数据
      countDownData: {
        day: 0,
        hours: 0,
        minutes: 0
      },
      // 倒计时状态列表
      countdownStatusList: [
        {
          code: 'entryStartTime',
          name: '报名开始'
        },
        {
          code: 'entryEndTime',
          name: '报名结束'
        }
      ],
      // 倒计时是否已经进行到最后
      countdownIsEnd: false,
      deadline: '1990-01-01 00:00:00',
      committeeLoading: false
    };
  },
  created() {
    const $route = this.$route;
    const _paramsId = $route.params.id;
    this.gameRoute = _paramsId.split('_')[0];
    // 因为短域名原因手动添加VUE_APP_Get_TenantId
    this.tenantId = process.env.VUE_APP_Get_TenantId;
    this.getGameInfoByGameRoute().then(() => {
      this.getCommittionList();
      this.getEventList();
    });
  },
  methods: {
    // 根据赛事路由获取赛事信息
    getGameInfoByGameRoute() {
      return new Promise((resolve, reject) => {
        const gameQO = {};
        gameQO.route = this.gameRoute;
        gameQO.IncludeStatus = true;
        gameQO.IncludeLevel = true;
        if (this.tenantId) {
          gameQO.__tenant = this.tenantId;
        }
        this.loading = true;
        api_GET_EventsManagementCompetitionWithRoute(gameQO).then(res => {
          this.loading = false;
          this.gameInfo = res || {};
          this.gameId = this.gameInfo.id;
          this.setEntryCountdown();
          resolve(res);
        });
      });
    },
    // 获取项目列表
    getEventList() {
      if (!this.gameId) return;
      const eventQO = {};
      eventQO.CompetitionId = this.gameId;
      eventQO.IncludeEventGroup = true;
      eventQO.IncludeEvent = true;
      eventQO.IncludeGender = true;
      eventQO.IncludeEventType = true;
      eventQO.IncludeRegisterType = true;
      eventQO.Sorting = 'creationTime';
      api_GET_EventsManagementCategory(eventQO).then(res => {
        const items = res.items || [];
        // category级排序
        items.sort((a, b) => {
          const _a = a.creationTime;
          const _b = b.creationTime;
          if (_a < _b) { return -1; }
          if (_a > _b) { return 1; }
          return 0;
        });
        this.categoryList = items.map(item => {
          item.fold = true;
          // eventGroups级别排序
          item.eventGroups.sort((a, b) => {
            const _a = a.startBirthDate.slice(0, 10);
            const _b = b.startBirthDate.slice(0, 10);
            if (_a === _b) { // 起始出生日期相同
              const _c = a.endBirthDate.slice(0, 10);
              const _d = b.endBirthDate.slice(0, 10);
              if (_c === _d) { // 结束日期也相同
                const _e = a.creationTime;
                const _f = b.creationTime;
                if (_e < _f) { return -1; }
                if (_e > _f) { return 1; }
                return 0;
              } else {
                if (_c > _d) { return -1; }
                if (_c < _d) { return 1; }
                return 0;
              }
            } else {
              if (_a > _b) { return -1; }
              if (_a < _b) { return 1; }
              return 0;
            }
          });
          // eventGroups 下 events 级别排序
          item.eventGroups.forEach(jtem => {
            // jtem.events.sort((a, b) => {
            //   const _a = a.sortOrder;
            //   const _b = b.sortOrder;
            //   if (_a < _b) { return -1; }
            //   if (_a > _b) { return 1; }
            //   return 0;
            // });
            jtem.events = jtem.events.sort((a, b) => a.sortOrder - b.sortOrder);
          });
          return item;
        });
      });
    },
    // 获取指定组委会单位列表
    getCommittionList() {
      if (!this.gameId) return;
      this.committeeLoading = true;
      api_GET_EventsManagementCompetitionOrganization({ competitionId: this.gameId }).then(res => {
        this.committeeLoading = false;
        const committionList = res.items || [];
        this.committionList = this.handleShowCommittion(committionList);
      }, error => {
        this.$message({ type: 'error', message: (error.error && error.error.message || '') });
        this.committeeLoading = false;
      });
    },
    // 处理显示组委会
    handleShowCommittion(committionList) {
      const _committionList = {};
      const returnCommittionList = [];
      for (let i = 0; i < committionList.length; i++) {
        const item = committionList[i];
        _committionList[item.organizationKey] = _committionList[item.organizationKey] || [];
        _committionList[item.organizationKey].push(item);
      }
      // 主办单位
      if (_committionList.sponsor) {
        returnCommittionList.push({
          name: '主办单位',
          data: _committionList.sponsor
        });
      }
      // 承办单位
      if (_committionList.contractor) {
        returnCommittionList.push({
          name: '承办单位',
          data: _committionList.contractor
        });
      }
      // 支持单位
      if (_committionList.support) {
        returnCommittionList.push({
          name: '支持单位',
          data: _committionList.support
        });
      }
      // 协办单位
      if (_committionList.assistance) {
        returnCommittionList.push({
          name: '协办单位',
          data: _committionList.assistance
        });
      }
      // 联系电话
      if (_committionList.phone) {
        returnCommittionList.push({
          name: '联系电话',
          data: _committionList.phone
        });
      }
      return returnCommittionList;
    },
    // 倒计时结束
    countDownEnd() {
      if (this.countdownIsEnd) return;
      this.setEntryCountdown();
    },
    // 设置报名倒计时 - 报名开始倒计时、报名结束倒计时、报名结束
    setEntryCountdown() {
      if (JSON.stringify(this.gameInfo) === '{}') return;
      this.initCountdownStatusList();
      this.calcCountdownStatus();
    },
    // 初始化倒计时状态列表
    initCountdownStatusList() {
      this.countdownStatusList.map(item => {
        item.data = this.gameInfo[item.code];
      });
    },
    // 计算当前倒计时状态
    calcCountdownStatus() {
      this.countdownIsEnd = false;
      console.log(this.countdownStatusList);
      // debugger
      for (let i = 0; i < this.countdownStatusList.length; i++) {
        const item = this.countdownStatusList[i];
        if (!this.compareNowDate(item.data)) {
          this.entryTitle = item.name + '倒计时';
          if (this.entryTitle === '报名开始倒计时') {
            this.deadline = item.data.substring(0, 10) + ' 00:00:00';
          } else {
            this.deadline = item.data.substring(0, 10) + ' 23:59:59';
          }

          return;
        }
      }
      this.entryTitle = this.countdownStatusList.length && this.countdownStatusList[this.countdownStatusList.length - 1].name + '倒计时' || '倒计时';
      this.deadline = this.countdownStatusList[this.countdownStatusList.length - 1].data.substring(0, 10) + ' 23:59:59';
      console.log(this.entryTitle);
      this.countdownIsEnd = true;
    },
    // 与当前时间进行比较计算
    compareNowDate(date) {
      if (!date) return false;
      const nowTimeStamp = new Date().getTime();
      const time = new Date(date).getTime();
      const timeStampDiff = time - nowTimeStamp;
      // 如果时间差小于0 （传入时间小于当前时间）- 开始进行倒计时
      if (timeStampDiff > 0) {
        return false;
      }
      return true;
    },
    toggleFold(categoryItem, index) {
      categoryItem.fold = !categoryItem.fold;
      this.$set(this.categoryList, index, categoryItem);
    }
  }
};
</script>
<style scoped>
.modal_shadow {
  background: #ffffff;
  border-radius: 8px;
  box-shadow: 0px 10px 30px 0px rgba(0,0,0,0.10);
}
.game_modal_header {
  position: relative;
  box-sizing: border-box;
  height: 40px;
  padding-left: 20px;
  margin-bottom: 14px;
  line-height: 40px;
  color: #353434;
  font-weight: bold;
  font-size: 20px;
}
.game_modal_header::after {
  display: block;
  position: absolute;
  left: 0;
  top: 0;
  width: 8px;
  height: 40px;
  background-color: #E02020;
  border-radius: 4px;
  content: "";
}
.committee_info {
  width: calc(100% - 504px - 58px);
  margin-right: 18px;
}
.entry_info .entry_countdown {
  width: 504px;
  height: 178px;
  padding: 40px 30px;
  box-sizing: border-box;
}
.committee_content {
  width: 100%;
  min-height: 178px;
  padding: 20px 20px;
  box-sizing: border-box;
}
.committee_item {
  overflow: hidden;
  margin-bottom: 8px;
}
.committee_item:last-child {
  margin-bottom: 0;
}
.committee_item .title {
  float: left;
  width: 70px;
  font-size: 16px;
  color: #646464;
  text-align: right;
  margin-right: 28px;
}
.committee_item .committee_item_content {
  float: left;
  width: calc(100% - 98px);
  color: #353434;
}
.committee_item_content .committee_name {
  margin-right: 20px;
}
.category_info {
  margin-top: 20px;
}
.category_item {
  border: 2px solid transparent;
  transition: all 0.3s ease;
  overflow: hidden;
}
.category_item:hover,
.category_item.active {
  border-color: #31456c;
}
.category_item .category_title {
  display: flex;
  width: 100%;
  height: 56px;
  line-height: 56px;
  padding: 0 30px;
  box-sizing: border-box;
  cursor: pointer;
  justify-content: space-between;
}
.category_item .category_icon {
  width: 40px;
  height: 40px;
  margin-right: 15px;
  vertical-align: middle;
}
.category_item .category_name {
  display: inline-block;
  width: 900px;
  vertical-align: middle;
}
.category_item .fold_name {
  display: inline-block;
  padding: 0 7px;
  color: #dc1d1d;
  font-weight: bold;
  text-shadow: 0px 10px 30px 0px rgba(0,0,0,0.10);
  vertical-align: middle;
}
.category_item .fold_icon {
  vertical-align: middle;
  transition: all 0.3s ease;
}
.category_item .fold_icon.active {
  transform: rotate(-180deg);
}
.category_content {
  margin: 0 20px;
  height: auto;
  overflow: hidden;
  transition: all 0.3s ease;
}
.category_content.height_0 {
  height: 0;
}
.category_content .line {
  width: 100%;
  height: 2px;
  background: #31456C;
}
.event_group {
  padding: 0 10px 20px;
}
.event_group .event_group_item {
  margin-top: 28px;
}
.event_group_item .event_group_title {
  color: #e02020;
  font-size: 20px;
  font-weight: bold;
}
.event_group_content {
  font-size: 14px;
}
.event_item {
  display: inline-block;
  padding: 0 5px;
  margin-right: 20px;
  vertical-align: top;
}
.event_group_content .name {
  position: relative;
}
.event_group_content .name::before {
  content: "";
  position: absolute;
  top: 2px;
  left: -14px;
  width: 0;
  height: 0;
  border: 6px solid transparent;
  border-radius: 3px;
}
.event_group_content .name.M::before {
  border-left-color: #31456C;
}
.event_group_content .name.W::before {
  border-left-color: #FC7123;
}
</style>
